package com.starlinkdt.common.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;

import java.security.SecureRandom;
import java.util.Random;

public class MyStringUtils {
    private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final Random RANDOM = new SecureRandom();

    public static String genNonceStr() {
        char[] nonceChars = new char[32];
        for (int index = 0; index < nonceChars.length; index++) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }

    public static String genBizNo(int length, String prefix) {
        String numRandom = genNumRandom(length - prefix.length());
        return prefix + numRandom;
    }

    public static String genApiAddress(String apiGroup, String apiName) {
        String apiAddress = apiGroup + "-" + apiName;
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        StringBuilder sb = new StringBuilder();
        char[] charArray = apiAddress.toCharArray();
        for (char c : charArray) {
            if (! Character.isLetter(c)) {
                sb.append(c);
            } else {
                try {
                    String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                    if (pinyinArray != null && pinyinArray.length > 0) {
                        sb.append(pinyinArray[0].charAt(0));
                    } else {
                        sb.append(Character.toLowerCase(c));
                    }
                } catch (Exception ignored) {}
            }
        }
        return sb.toString();
    }

    @SuppressWarnings("checkstyle:MagicNumber")
    private static String genNumRandom(int length) {
        StringBuilder buf = new StringBuilder();
        Random random = new Random();
        /*开头不为0,建议数据量较少时只放开部分，比如1至3开头的数，等业务达到一定数量时，再逐步放开剩余的号码段，由于是固定位数，总数量一定，生成的数越多，重复的几率越大**/
        int firstNumber = random.nextInt(9) + 1;
        buf.append(firstNumber);

        for (int i = 0; i < length - 1; ++i) {
            buf.append(random.nextInt(10));
        }

        return buf.toString();
    }

}
